<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商户" prop="merchantId">
        <el-select v-model="queryParams.merchantId" placeholder="请选择所属商家">
          <el-option  v-for="merchant in merchantList"
                      :key="merchant.deptId"
                      :label="merchant.deptName"
                      :value="merchant.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="券类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择券类型" clearable size="small">
          <el-option label="代金券" value="0" />
          <el-option label="折扣券" value="1" />
          <el-option label="兑换券" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="券状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择优惠券状态" clearable size="small">
          <el-option label="正常可用" value="0" />
          <el-option label="已过期" value="1" />
          <el-option label="已下架" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['merchant:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['merchant:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['merchant:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['merchant:coupon:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商户" align="center" prop="merchantName" />
      <el-table-column label="券类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 0" type="success">代金券</el-tag>
          <el-tag v-if="scope.row.type == 1" type="warning">折扣券</el-tag>
          <el-tag v-if="scope.row.type == 2" type="danger">兑换券</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠券标题" align="center" prop="title" />
      <el-table-column label="折扣" align="center" prop="discount" />
      <el-table-column label="减免金额" align="center" prop="amount" />
      <el-table-column label="最低消费" align="center" prop="minCost" />
      <el-table-column label="每个用户领券上限" align="center" prop="collectionTimes" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="有效时间" align="center" prop="timeType">
        <template slot-scope="scope">
          <span v-if="scope.row.timeType==0">
            领取后{{ scope.row.days}}天
          </span>
          <span v-if="scope.row.timeType==1">
            {{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}至{{ parseTime(scope.row.overTime, '{y}-{m}-{d}') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="success">正常可用</el-tag>
          <el-tag v-if="scope.row.status == 1" type="warning">已过期</el-tag>
          <el-tag v-if="scope.row.status == 2" type="danger">已下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:coupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:coupon:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleOffline(scope.row)"
            v-hasPermi="['merchant:coupon:handleOffline']"
          >下架</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商户" prop="merchantId">
              <el-select v-model="form.merchantId" placeholder="请选择所属商家">
                <el-option  v-for="merchant in merchantList"
                            :key="merchant.deptId"
                            :label="merchant.deptName"
                            :value="merchant.deptId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择券类型" @change="changeType">
            <el-option  v-for="couponType in couponTypeList"
                        :key="couponType.id"
                        :label="couponType.name"
                        :value="couponType.id" />
          </el-select>
        </el-form-item>
          </el-col>
          </el-row>
        <el-row>
          <el-col :span="12">
              <el-form-item label="券名称" prop="title">
                <el-input v-model="form.title" placeholder="请输入券名称" />
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item v-if="showMinCost" label="消费满" prop="amount">
                <el-input v-model="form.minCost"  type="number"  placeholder="0" :style="{width: '30%'}"  size="mini">
                </el-input>
                <el-input  v-if="showAmount" v-model="form.amount"  type="number" placeholder="0" :style="{width: '70%'}"  size="mini">
                  <template slot="prepend">减</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            <el-form-item v-if="showDiscount" label="折扣" prop="discount">
              <el-input v-model="form.discount" type="number" placeholder="请输入折扣">
                <template slot="append">折</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="库存" prop="quantity">
              <el-input v-model="form.quantity"  type="number"  placeholder="请输入数量：0为无限量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="领取限制" prop="collectionTimes">
            <el-input v-model="form.collectionTimes"  type="number"  placeholder="1">
              <template slot="prepend">每人可领取</template>
              <template slot="append">次</template>
            </el-input>
          </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="使用须知" prop="useNotice">
          <el-input v-model="form.useNotice" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row>
            <el-form-item label="有效时间" prop="timeType">
              <el-select @change="changeTimeType" v-model="form.timeType" placeholder="请选择有效时间" size="mini">
                <el-option  v-for="timeType in timeTypeList"
                            :key="timeType.id"
                            :label="timeType.name"
                            :value="timeType.id" />
              </el-select>
              <el-input v-if="showDays" v-model="form.days"  type="number"  placeholder="30">
                <template slot="prepend">领取后</template>
                <template slot="append">天内有效</template>
              </el-input>
              <el-date-picker v-if="showTime"  clearable size="small" style="width: 200px"
                              v-model="form.startTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择有效期开始日期">
              </el-date-picker>
              <el-date-picker v-if="showTime"  clearable size="small" style="width: 200px"
                              v-model="form.overTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择有效期结束日期">
              </el-date-picker>
            </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="封面图片" prop="coverImg">
              <el-input v-model="form.coverImg" placeholder="请输入封面图片" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面简介" prop="coverInfo">
              <el-input v-model="form.coverInfo" placeholder="请输入封面简介" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listDept } from "@/api/system/dept";
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon, exportCoupon,offlineCoupon } from "@/api/merchant/coupon";

export default {
  name: "Coupon",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        merchantId: null,
        type: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        merchantId: [
          { required: true, message: "商户不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "折扣券标题不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "0：代金券；1：折扣券；2：兑换券不能为空", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "数量：0为无限量不能为空", trigger: "blur" }
        ],
      },
      showAmount:true,
      showDiscount:false,
      showDays:false,
      showTime:true,
      showMinCost:true,
      // 商户表格数据
      merchantList: [],
      couponTypeList:[{id:0,name:'代金券'},{id:1,name:'折扣券'},{id:2,name:'兑换券'}],
      timeTypeList:[{id:0,name:'固定天数'},{id:1,name:'固定日期'}]
    };
  },
  created() {
    this.getList();
    this.getMerchantList();
  },
  methods: {
    /** 查询商户列表 */
    getMerchantList() {
      this.loading = true;
      listDept({deptType:2}).then(response => {
        this.merchantList = response.data;
        this.loading = false;
      });
    },
    changeType(value){
      if(value==0){//代金券
          this.showAmount = true;
        this.showMinCost = true;
        this.showDiscount = false;
        this.form.discount = 0;
      }
      if(value==1){//折扣券
        this.showAmount = false;
        this.showMinCost = false;
        this.showDiscount = true;
        this.form.amount = 0 ;
        this.form.minCost = 0;
      }
      if(value==2){//兑换券
        this.showAmount = false;
        this.showDiscount = false;
        this.showMinCost = true;
        this.form.amount = 0 ;
        this.form.discount = 0;
      }
    },
    changeTimeType(value){
      if(value==0){//代金券
        this.showDays = true;
        this.showTime = false;
      }
      if(value==1){//折扣券
        this.showDays = false;
        this.showTime = true;
      }
    },
    /** 查询优惠券列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        merchantId: null,
        title: null,
        discount: null,
        startTime: null,
        endTime: null,
        collectionTimes: null,
        coverImg: null,
        coverInfo: null,
        useNotice: null,
        amount: null,
        minCost: null,
        type: null,
        quantity: null,
        goodsType: null,
        goodsValue: null,
        timeType: null,
        days: null,
        status: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCoupon(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除优惠券编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCoupon(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 下架按钮操作 */
    handleOffline(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认下架优惠券?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return offlineCoupon(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("下架成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有优惠券数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCoupon(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
